export default {
  // 命名空间
  namespaced: true,
  state: () => ({
    // 购物车数据结构
    // {  goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state  }[]
    // 获取存储的数据
    carList: JSON.parse(uni.getStorageSync('carList') || '[]')
  }),
  getters: {
    totalCount(state) {
      return state.carList.reduce((p, n) => {
        return p + n.goods_count
      }, 0)
    },
    totalPrice(state) {
      return state.carList.filter(v => v.goods_state).reduce((p, n) => {
        return p + n.goods_count * n.goods_price
      }, 0)
    },
    isAllChecked(state) {
      return state.carList.every((v) => {
        return v.goods_state
      })
    }
  },

  mutations: {
    saveToStorage(state) {
      // 持久化存储
      uni.setStorageSync('carList', JSON.stringify(state.carList))
    },
    deleteCarListItem(state, payload) {
      state.carList = state.carList.filter(v => v.goods_id !== payload.goods_id)
      this.commit('car/saveToStorage')
    },
    updateCarItemAllState(state, payload) {
      state.carList.forEach(v => v.goods_state = payload)
      this.commit('car/saveToStorage')
    },
    updateCarListCount(state, payload) {
      const goods = state.carList.find(v => v.goods_id === payload.goods_id);

      if (goods) {
        goods.goods_count = payload.goods_count
      }
      this.commit('car/saveToStorage')
    },
    updateCarListState(state, payload) {
      const goods = state.carList.find(v => v.goods_id === payload.goods_id);

      if (goods) {
        goods.goods_state = !goods.goods_state
      }
      this.commit('car/saveToStorage')
    },
    addToCarList(state, payload) {
      // 1. 查找数据
      const goods = state.carList.find(v => v.goods_id === payload.goods_id)
      // 2. 是否存在
      if (goods) {
        // 存在数量递增
        goods.goods_count++;
      } else {
        // 不存在 推入新数据
        state.carList.push(payload)
      }
      this.commit('car/saveToStorage')
    }
  },
  actions: {},
}
